package com.carl.study.redis;

import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisConnectionException;
import org.redisson.config.Config;
/**
 * @program: FrameStudy
 * @description:
 * @author: Mr.Carl
 **/

public class RedissonDemo {
    private static final int NUM_THREADS = 10;
    private static final int NUM_ITEMS = 100;

    public static void main(String[] args) throws InterruptedException {
        // 创建Redisson客户端
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.2.11:6379");
        RedissonClient client = Redisson.create(config);

        // 获取分布式Map
        RMap<String, String> map = client.getMap("myMap");

        // 设置键值对
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");

        // 关闭Redisson客户端
        client.shutdown();

        demo();
    }

    public static void demo() throws InterruptedException {
        // 创建Redisson配置对象
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.2.11:6379");

        // 创建Redisson客户端
        RedissonClient redisson = null;
        try {
            redisson = Redisson.create(config);
        } catch (RedisConnectionException e) {
            System.out.println("Failed to create Redisson client: " + e.getMessage());
        }

        // 获取分布式Map
        RMap<String, Integer> map = redisson.getMap("myMap");
        //Thread.interrupt()
        // 创建多个线程来并发地向分布式Map中添加随机值
        Thread[] threads = new Thread[NUM_THREADS];
        for (int i = 0; i < NUM_THREADS; i++) {
            threads[i] = new Thread(() -> {

                try {
                    Thread.sleep(1000*5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                for (int j = 0; j < NUM_ITEMS; j++) {
                    // 使用一个变量来锁定对Map的访问
                    synchronized (map) {
                        // 生成一个随机键和随机值
                        String key = "key" + (int) (Math.random() * 1000);
                        int value = (int) (Math.random() * 1000);

                        // 将键值对放入Map中
                        map.put(key, value);
                    }
                }
            });
            threads[i].setName(i+":redis");
            threads[i].start();
        }

        // 等待所有线程执行完毕
        for (Thread thread : threads) {
            thread.join();
        }

        // 输出Map中的内容
        System.out.println(map);

        // 关闭Redisson客户端
        redisson.shutdown();
    }
}